|
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical ''set-builder notation'' (''set comprehension'') as distinct from the use of map and filter functions. ==Overview== Consider the following example in set-builder notation. : This can be read, " is the set of all numbers "2 times " where is an item in the set of natural numbers (), for which squared is greater than ." The smallest natural number, x = 1, fails to satisfy the condition x2>3 (the condition 12>3 is false) so 2 ·1 is not included in S. The next natural number, 2, does satisfy the condition (22>3) as does every other natural number. Thus S consists of 2 ·2, 2 ·3, 2 ·4... so S = 4, 6, 8, 10,... ie, all even numbers greater than 2. In this annotated version of the example: : * is the variable representing members of an input set. * represents the input set, which in this example is the set of natural numbers * is a predicate expression acting as a filter on members of the input set. * is an output expression producing members of the new set from members of the input set that satisfy the predicate expression. * braces indicate that the result is a set * the vertical bar and the comma are separators. A list comprehension has the same syntactic components to represent generation of a list in order from an input list or iterator: * A variable representing members of an input list. * An input list (or iterator). * An optional predicate expression. * And an output expression producing members of the output list from members of the input iterable that satisfy the predicate. The order of generation of members of the output list is based on the order of items in the input. In Haskell's list comprehension syntax, this set-builder construct would be written similarly, as: Here, the list () represents , x^2>3 represents the predicate, and 2 represents the output expression.List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may generate the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list. 抄文引用元・出典: フリー百科事典『 ウィキペディア(Wikipedia)』 ■ウィキペディアで「list comprehension」の詳細全文を読む スポンサード リンク
|